<template>

    <!--搜索键盘-->

    <el-dialog v-model="searchKeyboardDialogVisible" title="请输入商品名称首字母搜索" width="600"
        :before-close="handleClose">
        <div class="my-keyboard"></div>
        <template #footer>
            <div class="dialog-footer">
                <!-- <el-button @click="dialogVisible = false">Cancel</el-button> -->
                <el-button type="primary" size="large" @click="handleSubmit">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>

</template>
<script setup lang='ts'>
// @ts-nocheck
import {  ref, watch, nextTick, onBeforeUnmount } from 'vue'

import Keyboard from 'simple-keyboard'
import 'simple-keyboard/build/css/index.css'

const props = defineProps<{ visible: boolean}>()
const emit = defineEmits(['onChange', 'onKeyPress', 'update:visible', 'onSubmit'])
const searchKeyboardDialogVisible = ref(props.visible)
const inputVal = ref('')

function handleClose() {
    emit('update:visible', false)
}

//确认
function handleSubmit() {
    emit('update:visible', false)
    emit('onSubmit', inputVal.value)
}






let keyboard: any = null
let isInit = ref(true) //是否第一次初始化

const onKeyPress = (button) => {
    let input = keyboard.getInput()
    if (button === '{bksp}') { //回退
        const currentInput = input;
        keyboard.setInput(currentInput + ''.slice(0, -1))
    } else if (button === '{zf}') {//正负号
        if (!input || input === '0') return  //如果没有值或0 则直接返回
        if (input.indexOf('-') != -1) { //如果为负值
            keyboard.setInput(input.split('-')[1])
        } else {
            keyboard.setInput('-' + input)
        }
    } else if (button === '{clear}') {//清空
        keyboard.setInput('')
    } else {

        if (input.startsWith('0')) { //如果以0 开头，输入其它数字则变为其它数字
            keyboard.setInput(input.slice(1))
        }
    }

    emit('onKeyPress', button)
}
const onChange = (input) => {
    if (input.includes('.')) {
        // 确保只有一个小数点
        inputVal.value = input.split('.')[0] + '.' + input.split('.')[1]
        keyboard.setInput(inputVal.value)

    } else {
        inputVal.value = input
    }

    emit('onChange', input)
}

watch(() => props.visible, (newVal) => {
    countKeyboardDialogVisible.value = newVal
    if (newVal) {
        if (isInit.value) {
            nextTick(() => { //这里不使用nextTick 会导致弹窗出现后找不到DOM .simple-keyboard 具体原因不知道
                initKeyboard()
            })
        } else {
            let type = props.type
            updateKeyboardOptions(type)
        }

    } else {
        inputVal.value = ''
        keyboard.setInput('')
        // console.log(keyboard)
        // if (keyboard) {
        //     keyboard.destroy();
        //     keyboard = null
        // }
        // console.log(keyboard)
    }


})
//组件解绑之前 销毁keyboard实例，避免内存泄漏
onBeforeUnmount(()=>{
if (keyboard) {
            keyboard.destroy();
            keyboard = null
        }
})

//初始化keyboard
function initKeyboard() {
   
    let defaultLayout = [
        '1 2 3',
        '4 5 6',
        '7 8 9',
        '{zf} 0 ',
        '{confirm} {clear} {bksp}'
    ]
    if (type == 'weight') {
        defaultLayout = [
            '1 2 3',
            '4 5 6',
            '7 8 9',
            '{zf} 0 .',
            '{confirm} {clear} {bksp}'
        ]
    }
    // console.log(defaultLayout)
    const options = {
        onChange,
        onKeyPress,
        layout: {
            default: defaultLayout,
        },
        display: {
            '{bksp}': '回退',
            '{clear}': '清空',
            '{confirm}': '确定',
            '{zf}': '+/-'
        },

    }

    keyboard = new Keyboard('my-keyboard', options)
    isInit.value = false
}

//更新键盘选项
function updateKeyboardOptions(type) {
    if (keyboard) {
        let defaultLayout

        if (type == 'count') {
            defaultLayout = [
                '1 2 3',
                '4 5 6',
                '7 8 9',
                '{zf} 0 ',
                '{confirm} {clear} {bksp}'
            ]
        } else if (type == 'weight') {
            defaultLayout = [
                '1 2 3',
                '4 5 6',
                '7 8 9',
                '{zf} 0 .',
                '{confirm} {clear} {bksp}'
            ]
        }
        const options = {
        onChange,
        onKeyPress,
        layout: {
            default: defaultLayout,
        },
        display: {
            '{bksp}': '回退',
            '{clear}': '清空',
            '{confirm}': '确定',
            '{zf}': '+/-'
        },

    }
    keyboard.setOptions(options)
    }
}



</script>
<style lang='scss' scoped>
.my-input {
    margin-bottom: 8px;

    :deep(.el-input__inner) {
        height: 50px !important;
        font-size: 20px;
    }

}

.my-keyboard {


    :deep(.hg-button-bksp) {
        width: 20px;
        font-weight: bold !important;
    }

    :deep(.hg-button) {
        padding: 25px 5px;
        font-size: 20px;
        width: 10% !important;

    }

    .hg-button-enter {
        width: calc(80% + 40px) !important;
        color: #67C23A;
    }

    .hg-button[data-skbtn="l"] {
        // width: calc(100% - 20% + 20px);
        //width: calc(20% )!important;
    }

    .hg-button[data-skbtn="@"] {
        max-width: none !important;
    }

    .hg-button-bksp {
        width: calc(30% + 10px) !important;
        padding-left: 10px;
        box-sizing: border-box;
        color: #F56C6C;

    }
}
</style>
